using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

using AIFSContentManagementSystem;
using AIFSContentManagementSystem.Articles;
using AIFSContentManagementSystem.Articles.Messages;
using AIFSContentManagementSystem.Criteria;
using AIFSContentManagementSystem.Criteria.Messages;
using AIFSDataAccessLayer;

namespace AIFSCMSFacade
{
    public class AifsCmsFacade
    {
        public ResponseBase ProcessArticleRequest(ArticleRequest request)
        {
            ResponseBase responseBase = null;

            IConnectionProvider connectionProvider = new AIFSCMSDataAccessLayer.DefaultConnectionProvider();
            SimpleExecutionContext dataExecutionContext = new SimpleExecutionContext(connectionProvider);
            
            IArticleService articleService = AifsCmsServiceBuilder.GetArticleService(dataExecutionContext);
            
            MethodInfo methodProcess = articleService.GetType().GetMethod("Process", new Type[] { request.GetType() });
            
            responseBase = methodProcess.Invoke(articleService, new object[] { request }) as ResponseBase;

            return responseBase;
        }

        public ResponseBase ProcessArticleRequestInTransaction(ArticleRequest request)
        {
            IConnectionProvider connectionProvider = new AIFSCMSDataAccessLayer.DefaultConnectionProvider();
            
            TransactionalExecutionContext dataExecutionContext = new TransactionalExecutionContext(connectionProvider);            
            
            ResponseBase responseBase = null;
            try
            {
                dataExecutionContext.BeginTransaction();

                IArticleService articleService = AifsCmsServiceBuilder.GetArticleService(dataExecutionContext);

                MethodInfo methodProcess = articleService.GetType().GetMethod("Process", new Type[] { request.GetType() });
                responseBase = methodProcess.Invoke(articleService, new object[] { request }) as ResponseBase;

                if (responseBase.HasError && dataExecutionContext.TransactionInProgress)
                {
                    dataExecutionContext.RollbackTransaction();

                    return responseBase;
                }

                dataExecutionContext.CommitTransaction();
            }
            catch (Exception ex)
            {
                if (dataExecutionContext != null && dataExecutionContext.TransactionInProgress)
                    dataExecutionContext.RollbackTransaction();

                throw new AIFSContentManagementSystem.Exceptions.AIFSContentManagementSystemException("System error when processing article request in a transaction.", ex);
            }

            return responseBase;
        }
    }    
}
